package com.fingard.dsp.bank.directbank.wzcb01;

import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

/**
 * 温州银行批付查询
 */
public class WZCB01BatPayRec extends WZCB01Base implements IBatPayRec {

    /**
     * 批量代付提交
     *
     * @param p_req1988
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        //返回ATS的对象
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
        try{
            //待处理文件
            String fileTxtPath=localFilePath +bankFront.corpNo +DateHelper.convertD10toD8(p_req1988.payDate) +getBatchID()+".txt";
            //待上传文件
            String fileZipPath=fileTxtPath.replace(".txt",".zip");
            //生成文件
            StringBuilder sbd=new StringBuilder(p_req1988.totalAmt+","+p_req1988.getTotalNum()+",");
            while (p_req1988.readRecord()){
                sbd.append("\r\n");
                sbd.append(p_req1988.readedDetail.askNumber+",");//流水号
                sbd.append(p_req1988.readedDetail.payDate+",");//交易日期
                String payTime=p_req1988.readedDetail.payTime;
                sbd.append(payTime.substring(0,2)
                        +payTime.substring(3,5)+payTime.substring(6)+",");//交易时间
                if("0".equals(p_req1988.readedDetail.sameBnk)){//转账类型 行内1 跨行8
                    sbd.append("8"+",");
                }else if("1".equals(p_req1988.readedDetail.sameBnk)){
                    sbd.append("1"+",");
                }else {
                    sbd.append(",");
                }
                sbd.append(p_req1988.readedDetail.recAct+",");//收款账号
                sbd.append("0"+",");//        收款账户序号
                sbd.append(",");//收款业务种类
                sbd.append(",");//        收款业务类型
                sbd.append(p_req1988.readedDetail.recName+",");//收款户名
                sbd.append(p_req1988.readedDetail.cnapsCode+",");//        收款账号系统联行号
                sbd.append(p_req1988.readedDetail.recAreaName+",");//收款账号所在城市
                sbd.append(p_req1988.readedDetail.payAmount+",");//        转账金额
                sbd.append(",");//凭证类型
                sbd.append(",");//凭证号码
                sbd.append(p_req1988.readedDetail.askNumber+",");//摘要
            }
            FileHelper.writeFile(fileTxtPath,sbd.toString(),getCharset());//数据写入文件
            //上传文件
            boolean isFileUploadFlag=FileUpload(fileTxtPath,fileZipPath,bankFront.corpNo);
            if(isFileUploadFlag){//上传成功
                WriteBankLogLn("批量付款文件(txt)存放路径："+fileTxtPath);
                //拼接请求报文体
                WZCB01Header header = new WZCB01Header();
                header.txCode="E110";//SQEPay.110.01.01
                header.orderNo = p_req1988.reqBatchNO;
                XmlTextWriter xmlReq = new XmlTextWriter();
                writeReqHeader(xmlReq,header);
                xmlReq.writeStartElement("Body");
                xmlReq.writeElementString("BusAttr","02001");//必填 02001 （保留为接口扩展用）
                xmlReq.writeElementString("CurCode","1");//必填 1 （保留为接口扩展用）
                xmlReq.writeElementString("CurType","0");//必填 0 （保留为接口扩展用）
                xmlReq.writeElementString("ChkInfo",p_req1988.reqBatchNO);//转账交易批次号（批量查询时用到）
                xmlReq.writeElementString("SumAmt",p_req1988.totalAmt);//文件中总交易金额
                xmlReq.writeElementString("TotalCnt",p_req1988.totalNum);//文件中总笔数
                xmlReq.writeElementString("DcFlag","1");//入账标志
                xmlReq.writeElementString("PayAcctNo",p_req1988.ownAct);//        账号
                xmlReq.writeElementString("PayAcctSeqno","0");//必填 0 （保留为接口扩展用）
                xmlReq.writeElementString("PaySysCode","");//付款账号系统联行号
                xmlReq.writeElementString("PayCityCode","");//        付款账号所在城市
                xmlReq.writeElementString("RcvFileName",new File(fileZipPath).getName());//上传的文件名
                xmlReq.writeElementString("digest",getSignByFilePath(fileZipPath));//文件摘要
                xmlReq.writeEndElement();
                xmlReq.writeEndDocument();
                //组装head
                String head=getHead("E110","SQEPay.110.01.01");
                //发送请求报文
                String[] bankResult = sendToBank(xmlReq.toXmlString(),head);
                if (bankResult[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        if("true".equals(getBankConfig().getValueAsString("isFileDeleteFlag"))){
                            FileHelper.deleteFileIfExists(fileTxtPath);
                            FileHelper.deleteFileIfExists(fileZipPath);
                        }
                        String respCode = tmpBkReader.getFirstText("/Response/Head/RefuseCode");
                        String respInfo = tmpBkReader.getFirstText("/Response/Head/RefuseReason");
                        retAts.respCode = "0";
                        retAts.respInfo = respInfo;
                        retAts.reqSeqID = p_req1988.reqBatchNO;
                        retAts.transState = respCode;
                        retAts.payInfoCode = retAts.transState;
                    }else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpSbMsg.toString();
                    }
                } else{
                    retAts.respCode = "-1";
                    retAts.respInfo = bankResult[1];
                }
            }else{
                retAts.respCode = "-1";
                retAts.respInfo = "批量付款文件上传失败";
            }
        }catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            WriteBankLogLn("批量代发异常："+e);
            e.printStackTrace();
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_req1988.reqBatchNO;
        }
        retAts.writeRetToATS();
        return retAts;
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        // 返回ATS的对象
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        try {
            //拼接请求报文体
            WZCB01Header header = new WZCB01Header();
            header.txCode="E111";//SQEPay.111.01.01
            header.orderNo = p_req1998.reqBatchNO;
            XmlTextWriter xmlReq = new XmlTextWriter();
            writeReqHeader(xmlReq,header);
            XElement body =new XElement("Body","");
            body.addChild(new XElement("BusCode", "1"));//1：整批(查询批次下面所有的文件) 2：单笔（单笔时，EndSeqno必填）
            body.addChild(new XElement("ChkInfo", p_req1998.reqBatchNO));//转账交易批次号（批量查询时用到）
            body.addChild(new XElement("TransNo", ""));//批量文件中的流水
            xmlReq.writeXElement(body);
            xmlReq.writeEndDocument();
            //组装head
            String head=getHead("E111","SQEPay.111.01.01");
            //发送请求报文
            String[] bankResult = sendToBank(xmlReq.toXmlString(),head);
            //处理响应报文
            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String respCode = tmpBkReader.getFirstText("/Response/Head/RefuseCode");
                    String respInfo = tmpBkReader.getFirstText("/Response/Head/RefuseReason");
                    if ("0000".equals(respCode)) {//交易成功
                        //下载文件
                        String fileName=tmpBkReader.getFirstText("/Response/Body/SndFileName");
                        File rspFile=FileDownload(fileName);
                        if(rspFile!=null && rspFile.exists()){
                            retAts.respCode = "0";
                            retAts.respInfo=respInfo;
                            retAts.reqSeqID = p_req1998.reqBatchNO;
                            retAts.writeBeforeDetail();
                            //读取文件内容
                            String readLine = "";
                            InputStreamReader isr = new InputStreamReader(new FileInputStream(rspFile), getCharset());
                            BufferedReader reader = new BufferedReader(isr);
                            while ((readLine=reader.readLine())!=null) {
                                String[] details=readLine.split(",");
                                if(details.length>18){
                                    RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                    tmpRetDetail.payAct = p_req1998.ownAct;
                                    tmpRetDetail.recAct = details[10];//收款人号
                                    tmpRetDetail.recName = details[11];//收款人名
                                    tmpRetDetail.payAmount = details[4];//金额
                                    tmpRetDetail.curType = convertCurToATS(details[7]);//币种
                                    tmpRetDetail.postScript = details[0];//批内流水号
                                    tmpRetDetail.result = details[18];//8：成功(其它标识，请参看具体原因)
                                    tmpRetDetail.payInfoCode = tmpRetDetail.result;
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            }
                            reader.close();
                        }else {
                            retAts.respCode = "-1";
                            retAts.respInfo = "下载响应文件失败";
                        }
                    }else if("E001".equals(respCode)){//文件未生成，处理中
                        retAts.respCode = "0";
                        retAts.respInfo = respInfo;
                        retAts.reqSeqID = p_req1998.reqBatchNO;
                        retAts.transState = respCode;
                        retAts.payInfoCode=retAts.transState;
                        retAts.writeBeforeDetail();
                    }else {
                        retAts.respCode = "-1";
                        retAts.respInfo = respInfo;
                    }
                }else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            }else {
                retAts.respCode = "-1";
                retAts.respInfo = bankResult[1];
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }
        if ("-1".equals(retAts.respCode) && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_req1998.reqBatchNO;
        }
        if ("-1".equals(retAts.respCode)) {
            retAts.writeBeforeDetail();
        }
        retAts.writeAfterDetail();
        return retAts;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }
}
